package com.example.client_anna.util.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.client_anna.R;
import com.example.client_anna.module.branch_explore.ExploreDetailsActivity;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.example.client_anna.network.room.entity.Goods;
import com.example.client_anna.util.entity.Explore_data;
import com.example.client_anna.util.entity.Home_Business_Data;
import com.example.client_anna.util.entity.OrderGoods;
import com.example.client_anna.util.entity.OrderInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/11/8
 */
public class OrderOuterAdapter extends RecyclerView.Adapter<OrderOuterAdapter.ViewHolder> {

    private Context mContext;
    private List<com.alibaba.fastjson.JSONObject> mOrderInfo;

    //viewholder与xml布局中的控件关联
    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView order_img;
        TextView order_title;
        TextView order_activity;
        TextView order_status;
        TextView order_price;
        TextView order_amount;
        RecyclerView order_core_rec;

        ConstraintLayout constraintLayout;
        public ViewHolder(View view){
            super(view);
            order_img = (ImageView)view.findViewById(R.id.order_outer_img);
            order_title = (TextView)view.findViewById(R.id.order_outer_title);
            order_activity = (TextView)view.findViewById(R.id.order_outer_activity);
            order_status = (TextView)view.findViewById(R.id.order_outer_status);
            order_price = (TextView)view.findViewById(R.id.order_outer_price);
            order_amount = (TextView)view.findViewById(R.id.order_outer_amount);
            order_core_rec = (RecyclerView)view.findViewById(R.id.order_recycler_core_view);

            constraintLayout = (ConstraintLayout)view.findViewById(R.id.order_outer_layout);
        }
    }

    //为适配器传入数据
    public OrderOuterAdapter(List<com.alibaba.fastjson.JSONObject> jsonObjects) {
        mOrderInfo = jsonObjects;
    }

    @NonNull
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup viewGroup, int viewType) {
        if (mContext == null) {
            mContext = viewGroup.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.order_interface_outer, viewGroup, false);
        ViewHolder holder = new ViewHolder(view);

        //卡片点击事件
        holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                JSONObject jsonObject = mOrderInfo.get(position);
                String order_info = JSON.toJSONString(jsonObject.get("info"));
                //订单信息
                OrderInfo orderInfo = new OrderInfo();
                orderInfo = JSON.parseObject(order_info,OrderInfo.class);

                Toast.makeText(mContext,"订单"+orderInfo.getOrder_id(),Toast.LENGTH_SHORT).show();

            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull OrderOuterAdapter.ViewHolder holder, int position) {

        //每个订单的信息
        JSONObject jsonObject = mOrderInfo.get(position);

        String shop_info = JSON.toJSONString(jsonObject.get("shop"));

        String order_info = JSON.toJSONString(jsonObject.get("info"));

        String goods_info = JSON.toJSONString(jsonObject.get("goods"));

        //商家店铺信息
        Home_Business_Data home_business_data = new Home_Business_Data();
        home_business_data = JSON.parseObject(shop_info,Home_Business_Data.class);

        //订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo = JSON.parseObject(order_info,OrderInfo.class);

        //每个订单中的商品详细信息
        List<OrderGoods> goods = new ArrayList<>();
        goods = JSON.parseArray(goods_info,OrderGoods.class);

        holder.order_title.setText(home_business_data.getTheme());//商家名
        holder.order_activity.setText(getFullMinus(home_business_data.getFullminus()));//商家商标

        String order_status = "";
        switch (orderInfo.getStatus()){
            case 0:
                order_status = "未付款";
                break;
            case 1:
                order_status = "已付款";
                break;
            case 2:
                order_status = "已接单";
                break;
            case 3:
                order_status = "已配送";
                break;
            default:
                order_status = "";
        }
        holder.order_status.setText(order_status);
        holder.order_price.setText(String.valueOf(orderInfo.getPay_total()));

        int amount = 0;
        for (OrderGoods i:goods){
            amount += i.getFood_amount();
        }
        holder.order_amount.setText("共"+String.valueOf(amount)+"件");

        //商家商标
        String url = RequestUrl.getUrl()+home_business_data.getImage();
        displayImageCenter(mContext,holder.order_img,url);

        //订单商品详细信息
        OrderCoreAdapter orderOuterAdapter = new OrderCoreAdapter(goods);
        //加载闪烁问题：添加标记tag,tag标记着每一张请求url的图片，加载的时候防止重新加载
        //需要重写adapter的getItemId方法
        orderOuterAdapter.setHasStableIds(true);
        //适配器数据改变
        orderOuterAdapter.notifyDataSetChanged();
        //GridLayoutManager布局方式，参数1:Context，参数2:列数
        GridLayoutManager layoutManager = new GridLayoutManager(mContext,1);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);//横向滑动
        //加载布局方式
        holder.order_core_rec.setLayoutManager(layoutManager);
        //recyclerView布局加载适配器
        holder.order_core_rec.setAdapter(orderOuterAdapter);

    }

    //将json形式的字符串转成需要样式
    private String getFullMinus(String fullminus){
        HashMap<String,String> map = new HashMap<>();
        Gson gson = new Gson();
        map = gson.fromJson(fullminus,new TypeToken<HashMap<String,String>>(){}.getType());
        String toString = "\"";
        Set set = map.keySet();
        for (Iterator iterator = set.iterator(); iterator.hasNext();){

            //iterator.hasNext()只是判断下一个元素的有无，并不移动指针
            //iterator.next()向下移动指针
            String key = String.valueOf(iterator.next());
            String value = String.valueOf(map.get(key));

            if (iterator.hasNext()){
                toString = toString+key+"减"+value+" | ";
            }else {
                toString = toString+key+"减"+value;
            }
        }
        return toString+"\"";
    }

    public static void displayImageCenter(Context context,final ImageView imageView,String url){
        RequestOptions options = new RequestOptions()
                //磁盘缓存
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                //内存缓存，默认false，表示不跳过内存缓存
                .skipMemoryCache(false)
                //加载错误显示的图片
                .error(R.drawable.explore_error)
                //占位图
                .placeholder(R.drawable.explore_placeholder)
                //设置图片的宽和高，获取imageView控件的宽度和高
                //注：在onCreate中是获取不到imageview的高度的，因为这个时候imageView控件自己都还没有测量
                .override(imageView.getMeasuredWidth(), imageView.getMeasuredHeight())
                //不需要动画效果，默认300
                .dontAnimate();
        //Glide缓存顺序：内存>磁盘>网络
        Glide.with(context)
                .asBitmap()
                .load(url)
                .apply(options)
                .into(imageView);
    }

    @Override
    public int getItemCount() {
        return mOrderInfo.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

}
